import React, { Component } from 'react'
import { get } from '@/utils/requestUtil.js'
import { Typography } from 'antd'
import DocumentList from '@/components/basicWidget/DocumentList'
import { commonQueryByCode } from '@/service/document/documentService'
import FormWidget from '../FormWidget'
import { getFormProps, getFormPropsForObj } from '@/utils/formPropsUtil'
import _ from 'lodash'
import { message } from 'antd'
import { getTemplateByCode } from '@/service/schema/schemaService'
import Debug from '../Debug'
import './index.css'
import consoleUtil from '@/utils/consoleUtil'


/**
 * @author jms
 * @description 查询列表
 * @date 2024-11-09
 * 
 * 配置化的queryList
 */
export default class QueryList extends Component {

    constructor(props) {
        // 调用父类的构造方法，确保组件的props被正确初始化
        super(props)
        // 状态初始化
        this.state = {
            // 用于唯一标识查询表单的键，以防止表单的重复渲染
            queryFormKey: new Date().getTime(),
            // 存储命令相关的信息
            command: {},
            // 存储架构相关的信息
            schema: {},
            // 存储属性相关的信息
            properties: {},
            // 查询出来的结果数据
            dataSoure: [],
            // 加载状态，用于控制加载中的UI显示
            loading: true,
            // 存储选中行的键
            selectedRowKeys: [],
            // 存储选中的行
            selectedRows: [],
            // 数据总数
            totalNumber: 0,
            // 列表配置，用于定制列表的显示
            listConfig: {}
        }
    }

    /**
     * 组件挂载完成后异步执行的方法
     * 该方法主要用于初始化表单模板和配置列表
     */
    async componentDidMount() {
        // 检查是否配置了表单模板标识
        if (!this.props.queryCode) {
            message.warning('未配置表单模板标识！')
            return
        }

        // 获取表单模板内容
        let template = {}
        try {
            template = await getTemplateByCode(this.props.queryCode)
        } catch (e) {
            consoleUtil.error('获取表单模板失败', e)
            return
        }
        if (!template || !template.content) {
            consoleUtil.error('获取表单模板失败')
            return
        }
        let schema = _.get(_.cloneDeep(template), 'content', {})

        // 获取表单字段属性对象
        const properties = _.get(schema, 'properties', {})

        // 开始构建listConfig
        const listSchema = _.get(schema, 'listSchema', {})
        const displayColumns = _.get(listSchema, 'displayColumns', {})
        const columns = Object.keys(displayColumns)
            .filter(key => properties[key])
            .map(key => ({
                title: properties[key].description,
                dataIndex: properties[key].queryListDataSource || key,
                order: properties[key].order
            }))

        // 对列进行排序
        columns.sort((a, b) => (a.order || 0) - (b.order || 0))

        // 构建列表配置对象
        const listConfig = {
            columns,
            serialNumber: getFormProps(_.get(listSchema, 'serialNumber', true), this),
            bordered: getFormProps(_.get(listSchema, 'bordered', true), this),
            showTotal: getFormProps(_.get(listSchema, 'showTotal', true), this),
            pageSizeOptions: getFormProps(_.get(listSchema, 'pageSizeOptions', [10, 20, 50, 100]), this),
            gotoPage: getFormProps(_.get(listSchema, 'gotoPage', true), this),
            singer: getFormProps(_.get(listSchema, 'singer', true), this),
            hideSelect: getFormProps(_.get(listSchema, 'hideSelect', false), this),
            actionColumns: getFormProps(_.get(listSchema, 'actionColumns', null), this)
        }

        // 获取列表命令配置
        const command = getFormPropsForObj(_.get(listSchema, 'command', {}), this)

        // 更新组件状态
        await new Promise(resolve => {
            this.setState({
                schema,
                command,
                properties,
                listConfig
            }, resolve)
        })

        // 检查是否需要自动查询
        const startQuery = _.get(schema, 'listSchema.startQuery', true)
        if (startQuery === undefined || startQuery === true) {
            await this.reSetStatus()
        } else {
            await new Promise(resolve => { this.setState({ loading: false }, resolve) })
        }
    }

    //选择变化
    onSelectChange = async (selectedRowKeys, selectedRows) => {
        await new Promise(resolve => {
            this.setState({
                selectedRowKeys,
                selectedRows
            }, resolve)
        })
        this.props.onSelectChange && await this.props.onSelectChange(selectedRowKeys, selectedRows)
    }

    // 查询功能
    onQuery = async () => {
        // 从状态中解构命令的相关信息
        const { commandCode, resquestUrl, kvMap } = this.state.command
        // 如果没有URL和命令码，则不执行任何操作
        if (!resquestUrl && !commandCode) return false
        // 设置加载状态为true
        await new Promise((resolve) => {
            this.setState({ loading: true }, resolve)
        })
        // 通过后台接口获取数据，查询条件只有等于
        if (resquestUrl) {
            // 请求参数获取
            let requestParams = {}
            let response = await get(this.props.resquestUrl, { params: requestParams })
            if (response) {
                if (response.code === 200 && response.data !== null) {
                    await new Promise((resolve) => {
                        this.setState({
                            dataSoure: response.data,
                            loading: false
                        }, resolve)
                    })
                }
            }
        }
        // 通过SQL代码获取数据，查询条件自定义
        if (commandCode) {
            let searchFactory = []
            const { formData } = this.queryForm.state
            const { properties } = this.state
            searchFactory = Object.keys(formData)
                .filter(key => properties[key] && formData[key])
                .map(key => ({
                    fieldName: _.get(properties[key], 'widgetConfig.queryListDataSource', key) || key,
                    fieldValue: formData[key],
                    operate: _.get(properties[key], 'widgetConfig.queryOperate', 'like')
                }))
            // 获取分页信息
            const { current, pageSize } = this.documentList.state
            let response = await commonQueryByCode({
                commandCode,
                searchFactory,
                limit: {
                    startIndex: (current - 1) * pageSize + 1,
                    number: pageSize
                },
                kvMap
            })
            if (response && response.data && response.data.documents) {
                const result = response.data.documents.map(item => item.content)
                await new Promise((resolve) => {
                    this.setState({
                        dataSoure: result,
                        totalNumber: response.data.totalNumber,
                        loading: false
                    }, resolve)
                })
            }
        }
        // 清除已选中的信息
        await this.documentList.onSelectChange([], [])
    }

    //重置
    reSetStatus = async () => {
        const { commandCode, resquestUrl, kvMap } = this.state.command
        if (!resquestUrl && !commandCode) return false
        await new Promise((resolve) => {
            this.setState({
                loading: true,
                queryFormKey: new Date().getTime()
            }, resolve)
        })
        //列表属性重置
        await this.documentList.reStart()
        //通过后台接口获取数据，查询条件只有等于
        if (resquestUrl) {
            let response = await get(resquestUrl)
            if (response) {
                if (response.code === 200 && response.data !== null) {
                    await new Promise((resolve) => {
                        this.setState({
                            dataSoure: response.data,
                            loading: false
                        }, resolve)
                    })
                }
            }
        }
        //通过sqlCode获取数据，查询条件自定义
        if (commandCode) {
            //获取分页
            const { current, pageSize } = this.documentList.state
            let response = await commonQueryByCode({
                commandCode,
                limit: {
                    startIndex: (current - 1) * pageSize + 1,
                    number: pageSize
                },
                kvMap
            })
            if (response && response.data && response.data.documents) {
                const result = response.data.documents.map(item => item.content)
                await new Promise((resolve) => {
                    this.setState({
                        dataSoure: result,
                        totalNumber: response.data.totalNumber,
                        loading: false
                    }, resolve)
                })
            }
        }
    }

    render() {
        return (
            <Debug name='QueryList'>
                <div className='quertList-manage-main'>
                    {
                        this.state.schema.title ?
                            <div className='queryList-manage-title'>
                                <Typography.Title>{this.state.schema.title}</Typography.Title>
                            </div> : ''
                    }
                    <div className='querylist-form-widget'>
                        <FormWidget
                            key={this.state.queryFormKey}
                            code={this.props.queryCode}
                            onQuery={this.onQuery}
                            reSetStatus={this.reSetStatus}
                            ref={queryForm => { this.queryForm = queryForm }}
                            {...this.props}
                        >
                        </FormWidget>
                    </div>
                    <div className='querylist-table-widget'>
                        <DocumentList
                            data={this.state.dataSoure}
                            loading={this.state.loading}
                            totalNumber={this.state.totalNumber}
                            onSelectChange={this.onSelectChange}
                            onPageChange={this.onQuery}
                            rowKey={(record) => { return record.id }}
                            ref={documentList => { this.documentList = documentList }}
                            {...this.state.listConfig}
                            {...this.props.listConfig}
                        ></DocumentList>
                    </div>
                </div>
            </Debug>
        )
    }
}
